<template>
  <div class="app-container">
    <wise-crud ref="wise-crud" :urls="urls" :fields="fields" :handle="handle" :data-fields="dataFields">
      <template v-slot:handle="slotProps">
        <el-button type="warning" size="small" class="activeBtn" round
          @click.native.prevent="initHandle(slotProps.row)">重置密码</el-button>
        <el-button type="info" size="small" class="activeBtn" round
          @click.native.prevent="settingHandle(slotProps.row)">设置</el-button>
      </template>
    </wise-crud>
    <el-dialog ref="drawer1" title="设置岗位角色" :visible.sync="drawer1" close-on-press-escape destroy-on-close>
      <div class="draw-body">
        <el-form ref="ruleForm1" :model="setting.obj" :rules="setting.rules" :validate-on-rule-change="false"
          label-width="100px" label-suffix=":">
          <el-form-item label="设置岗位" prop="professionIds">
            <el-transfer v-model="setting.obj.professionIds" filterable :filter-method="filterMethod"
              filter-placeholder="请输入岗位名称" :titles="['岗位', '赋予岗位']" :data="setting.professionList"
              :props="{ key: 'id', label: 'name' }" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="settingSubmitForm('ruleForm1')">确定</el-button>
            <el-button @click="resetForm('ruleForm1')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import WiseCrud from '../../../../components/Crud/wiseCrud'
  import {
    postHandle
  } from '../../../../api'
  import checkPermission from '../../utils/permission' // 权限判断函数
  export default {
    name: 'UserManage',
    components: {
      WiseCrud
    },
    data() {
      return {
        dataFields: [{
            name: 'roleList' // 返回用户拥有的角色
          },
          {
            name: 'entSpaceInfoList' // 返回用户加入的空间
          },
          {
            name: 'sysOpsAdminStatus'
          }
        ],
        urls: {
          list: '/api/v1/welder-uac-second/user-information-comb/get-ent-member',
          add: '/api/v1/welder-uac-second/user-information-comb/create-ent-member',
          // show: '/api/v1/welder-uac-second/user-information-comb/show-user-info/',
          update: '/api/v1/welder-uac-second/user-information-comb/update-ent-member/',
          // delete: '/api/v1/welder-uac-second/user-information-comb/remove-user-info/'
        },
        fields: [{
            label: '序号',
            type: 'index',
            use: ['table']
          },
          {
            label: '个人头像',
            prop: 'picture',
            type: 'file',
            use: ['table', 'add', 'view', 'edit', 'search']
          },
          {
            label: '真实姓名',
            prop: 'username',
            type: 'text',
            maxlength: 20,
            rules: [{
              required: true,
              message: '请输入真实姓名',
              trigger: 'blur'
            }],
            placeholder: '请输入真实姓名',
            use: ['table', 'add', 'view', 'edit', 'search']
          },
          {
            label: '联系方式',
            prop: 'phone',
            type: 'text',
            maxlength: 11,
            rules: [{
                required: true,
                message: '请输入登录手机号',
                trigger: 'blur'
              },
              {
                min: 11,
                max: 11,
                message: '请输入11位手机号码',
                trigger: 'blur'
              },
              {
                pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
                message: '请输入正确的手机号码'
              }
            ],
            placeholder: '请输入登录手机号',
            use: ['table', 'add', 'view', 'edit', 'search']
          },
          {
            label: '岗位名称',
            type: 'render',
            tableRender: (h, row, index) => {
              return h(
                'div',
                row.professionList && row.professionList.length > 0 ?
                row.professionList
                .map((item) => item.professionName)
                .join('，') :
                ''
              )
            },
            viewRender: (h, item, object) => {
              return h(
                'div',
                object.professionList && object.professionList.length > 0 ?
                object.professionList
                .map((item) => item.professionName)
                .join('，') :
                ''
              )
            },
            use: ['table', 'view']
          },

          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            placeholder: '请输入简介',
            use: ['add', 'view', 'edit']
          },
          {
            label: '操作',
            type: 'handle',
            use: ['table'],
            handle: ['edit', 'view', 'delete'],
            tableWidth: 320
          }
        ],
        drawer: false,
        filterMethod(query, item) {
          return item.name.indexOf(query) > -1
        },

        userInfo: {},

        drawer1: false,
        setting: {
          id: '',
          professionList: [],
          obj: {
            professionIds: []
          },
          rules: {}
        }
      }
    },
    computed: {
      handle() {
        if (this.checkPermission(['superSysOpsAdmin'])) {
          return ['add', 'search']
        } else {
          return ['search']
        }
      }
    },
    methods: {
      checkPermission,
      initHandle(row) {
        this.$confirm('您确定要重置该用户的密码?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            postHandle(
                '/api/v1/welder-uac-second/user-account-comb/init-password/' + row.userId, {}
              )
              .then((res) => {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
              })
              .catch(() => {
                this.$message({
                  type: 'error',
                  message: '操作失败'
                })
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },

      settingHandle(row) {
        this.drawer1 = true
        this.setting.id = row.spaceMemberInfo ? row.spaceMemberInfo.id : ''
        if (row.professionList && row.professionList.length > 0) {
          this.setting.obj.professionIds = row.professionList.map(
            (item) => item.professionId
          )
        } else {
          this.setting.obj.professionIds = []
        }
        this.getJobList(
          row.entSpaceInfoList && row.entSpaceInfoList.length > 0 ?
          row.entSpaceInfoList[0].id :
          ''
        )
      },

      getJobList(id) {
        const req = {
          d: {
            filters: [{
                field: 'spaceId',
                operator: 'EQUALS',
                value: id
              },
              {
                field: 'level',
                operator: 'EQUALS',
                value: 1
              }
            ],
            fields: [],
            page: {
              p: 1,
              ps: 9999
            }
          }
        }
        postHandle('/api/v1/welder-uac-second/base-profession-comb/list', req).then(
          (response) => {
            this.setting.professionList = response.result
          }
        )
      },

      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      settingSubmitForm(formName) {
        if (this.setting.id) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              postHandle(
                `/api/v1/welder-uac-second/space-organization-member-comb/configure-member-privilege/${this.setting.id}`, {
                  obj: this.setting.obj
                }
              ).then((response) => {
                this.drawer1 = false
                this.$refs['wise-crud'].handleSearch()
              })
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$message.warning('未分配企业')
        }
      },

      configureSuperUserRoleHandle(row, flag) {
        postHandle(
          `/api/v1/welder-uac-second/user-role-comb/configure-super-user-role/${row.userId}`, {
            d: {},
            obj: {
              authorization: flag
            }
          }
        ).then((res) => {
          this.$message('操作成功')
          this.$refs['wise-crud'].handleSearch()
        })
      }
    }
  }
</script>

<style>
  .el-transfer .el-checkbox {
    display: block;
  }
</style>